package org.kardigen.lg.service.server;

import java.util.List;

import javax.jdo.FetchPlan;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import org.kardigen.lg.entity.Training;
import org.kardigen.lg.entity.TrainingChapter;

public class TrainingRequestService {

	public static List<Training> findAllTrainings() {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		List<Training> result = null;
		try {
			tx.begin();
			pm.getFetchPlan().addGroup(FetchPlan.ALL);
			pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS);
			Query query = pm.newQuery(Training.class);
			result = (List<Training>) query.execute();
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}

		return result;
	}

	public static Training saveTraining(Training training) {
		return persist(training);
	}

	public static TrainingChapter saveChapter(TrainingChapter chapter) {

		return persist(chapter);
	}

	private static <T> T persist(T entity) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		// PersistenceManager pm = JDOHelper.getPersistenceManager(entity);
		Transaction tx = pm.currentTransaction();
		T detachCopy = null;
		try {
			tx.begin();
			pm.getFetchPlan().addGroup(FetchPlan.ALL);
			pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS);
			// pm.setDetachAllOnCommit(true);
			// pm.setCopyOnAttach(true);
			detachCopy = pm.makePersistent(entity);
			// if (tx.isActive())
			tx.commit();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}

		return detachCopy;
   }

}
